package cn.bonoon.policy.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import cn.bonoon.entities.PrivilegeEntity;
import cn.bonoon.entities.RoleEntity;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.security.LogonUserPrivilegeMapped;
import cn.bonoon.policy.AccountPrivilegePolicy;

public class RolePrivilegeStoragePolicy implements AccountPrivilegePolicy{

	@PersistenceContext
	protected EntityManager entityManager;
	
	@Override
	public boolean accept(Class<?> acceptClass) {
		return RoleEntity.class.isAssignableFrom(acceptClass);
	}

	@Override
	public void doPolicy(LogonUser user, LogonUserPrivilegeMapped privilegeMapped) {
		if(user.isSuper()){
			privilegeMapped.all();
		}else{
			Object privilege = privilegeMapped.getSource();
			if(privilege instanceof List){
				
				String ql = "select distinct x from PrivilegeEntity x where x.invalid=false and (x.account.id=?";
				
				for(Object pr : (List<?>)privilege){
					RoleEntity role = (RoleEntity)pr;
					if(role.isDeleted() || role.getStatus() != 1) continue;
					
					ql += " or x.role.id=" + role.getId();
				}
				
				ql += ")";
				
				for(PrivilegeEntity pr : entityManager.createQuery(ql, PrivilegeEntity.class)
						.setParameter(1, user.getId())
						.getResultList()){
					if(pr.isInvalid()) continue;
					
					privilegeMapped.add(pr);
				}
				
				privilegeMapped.update();
			}
		}
	}

}
